package cn.com.citydo.base.handler;

import cn.com.citydo.base.anotation.ResponseResultAnnotation;
import cn.com.citydo.base.exception.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

import static cn.com.citydo.base.constant.ResponseResultConstant.RESPONSE_RESULT_ANN;

/**
 * Create By Cuixk
 * 2019/7/3 11:13
 */
@Slf4j
@ControllerAdvice
public class ResponseResultHandler<T> implements ResponseBodyAdvice<T> {

    /**
     * 判断是否需要返回值包装
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        ResponseResultAnnotation attribute = (ResponseResultAnnotation) request.getAttribute(RESPONSE_RESULT_ANN);
        return null == attribute ? false : true;
    }

    /**
     * 进行结果的包装返回
     * @param t
     * @param methodParameter
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @return
     */
    @Override
    public T beforeBodyWrite(T t, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        if (t instanceof String) {
            return t;
        }
        if (t instanceof RuntimeException) {
            RuntimeException exception = (RuntimeException) t;
            throw exception;
        }
        ResponseResult.success(t);
        return t;
    }
}
